<template>
  <div>
    <el-upload
      drag
      :limit="limitNum"
      :auto-upload="false"
      accept=".xlsx"
      action=""
      :http-request="uploadFile"
      :before-upload="beforeUploadFile"
      :on-change="fileChange"
      :on-exceed="exceedFile"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :on-error="handleError"
      :file-list="fileList"
    >
      <i class="el-icon-upload" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击选取</em></div>
      <div slot="tip" class="el-upload__tip">只能选取xlsx文件，且不超过10M</div>
    </el-upload>
    <br>
    <el-button size="small" type="primary" @click="uploadFile">立即上传</el-button>
    <el-button size="small">取消</el-button>
  </div>
</template>

<script>
import userApi from '@/api/user'
export default {
  data() {
    return {
      limitNum: 1, // 上传excell时，同时允许上传的最大数
      fileList: [] // excel文件列表
    }
  },
  methods: {
    // 文件超出个数限制时的钩子
    exceedFile(files, fileList) {
      this.$message.warning(`只能选择 ${this.limitNum} 个文件，当前共选择了 ${files.length + fileList.length} 个`)
    },
    // 文件状态改变时的钩子
    fileChange(file, fileList) {
      this.fileList.push(file.raw)
    },
    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
    beforeUploadFile(file) {
      const extension = file.name.substring(file.name.lastIndexOf('.') + 1)
      const size = file.size / 1024 / 1024
      if (extension !== 'xlsx') {
        this.$message.warning('只能上传后缀是.xlsx的文件')
      }
      if (size > 10) {
        this.$message.warning('文件大小不得超过10M')
      }
    },
    handleRemove(file, fileList) {
      if (fileList.length === 0) {
        this.fileList = []
      } else {
        const dl = this.fileList.indexOf(file)
        this.fileList.splice(dl, 1)
      }
    },
    // 文件上传成功时的钩子
    handleSuccess() {
      this.$message.success('文件上传成功')
    },
    // 文件上传失败时的钩子
    handleError() {
      this.$message.error('文件上传失败')
    },

    // 手动上传
    uploadFile() {
      if (this.fileList.length === 0) {
        this.$message.warning('请上传文件')
      } else {
        const form = new FormData()
        form.append('file', this.fileList[0])
        // console.log(form.get('file'))
        // console.log(typeof form)
        userApi.uploadBooks(form).then(res => {
          // console.log(res.data)
          if (res.data.code === 200) {
            // console.log('上传成功')
            this.handleSuccess()
          }
        }, err => {
          this.handleError()
          console.log(err)
        })
      }
    }
  }
}
</script>

<style scoped>

</style>

